<?php
namespace app\company\controller;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use app\common\lib\SendIntegralNew;
class Index extends Base
{
    public function index()
    {
        //消息处理
        $this->notices();
        //我的积分
        $this->myIntegral();
        //我的排名
        $this->myRank();
        //我的审核
        $this->checkAward();
        //积分奖扣
        $this->checkAward(1);
        //奖扣任务
        $this->prize_buckle_task();
        //奖扣统计
        $this->rewardTotal();

        return $this->fetch();
    }

    //消息处理
    private function notices()
    {
        //待办任务
        //我负责进行中，我参与进行中的
        //我负责的任务
        $taksCount = M('com_task')->where([
            'com_id' => $this->com_id,
            'status' => ['in',[2,3]],
            'principal_user_id' => $this->user_id,
        ])->count();
        //我参与的任务
        $taksCount_1 = M('com_task a')
            ->join('com_task_relation_take b','b.task_id=a.id','right')
            ->where([
            'a.com_id' => $this->com_id,
            'a.status' => 3,
            'b.user_id' => $this->user_id,
        ])->count();
        $taksCount += $taksCount_1;
        $taskIds = M('com_task_relation_take')->where([
            'user_id'=>$this->user_id,
            'com_id' => $this->com_id
        ])->column('task_id');
        $tmpCount = M('com_task')->where('id', 'in', $taskIds)->where('status',3)->count();
        $taksCount += $tmpCount;
        $this->assign(compact('taksCount'));

        //待读消息
        $noticeCount = M('com_notice a')
            ->join('com_notice_relation b','b.notice_id=a.id','right')
            ->where([
            'a.com_id' => $this->com_id,
            'a.status' => 2,
            'b.user_id' => $this->user_id,
            'b.status' => 0,
        ])->count();
        $noticeIds = M('com_notice_relation')->where([
            'user_id'=>$this->user_id,
            'com_id' => $this->com_id,
            'status' => 0,
        ])->column('notice_id');
        $tmpCount = M('com_notice')->where('id', 'in', $noticeIds)->where('status',2)->count();
        $noticeCount += $tmpCount;
        $this->assign(compact('noticeCount'));

        //当月奖票
        $jpCount = M('com_integral_event_relation_users a')
            ->join('com_integral_prize_buckle_relation_event b','b.id = a.event_id', 'left')
            ->join('com_integral_prize_buckle c','c.id = b.prize_buckle_id', 'left')
            ->where([
                'a.user_id'=>$this->user_id,
                'a.com_id'=>$this->com_id,
                'a.is_lottery_ticket'=>1,
                'a.is_print'=>0,
                'c.status'=>2,
                'c.prize_buckle_time'=>['>',strtotime(date('Y-m-01'))],
            ])->count();
        $this->assign(compact('jpCount'));

        //当月奖扣
        $jkCount = M('com_integral_prize_buckle')
            ->where([
                'com_id' => $this->com_id,
                'prize_buckle_time'=>['>',strtotime(date('Y-m-01'))],
                'first_check_user_id'=>$this->user_id,
                'status'=>2,
            ])->count();

//        $tmpCount = M('com_integral_prize_buckle a')
//            ->where([
//                'com_id' => $this->com_id,
//                'create_time'=>['>',strtotime(date('Y-m'))],
//                'last_check_user_id'=>$this->user_id,
//                'status'=>2,
//            ])->count();
//        $jkCount += $tmpCount;
        $this->assign(compact('jkCount'));

        //奖扣未审核数量
        $wsh_jkCount = M('com_integral_prize_buckle')
            ->where([
                'com_id' => $this->com_id,
                'first_check_user_id'=>$this->user_id,
                'status'=>0,
            ])->count();

        $tmpCount = M('com_integral_prize_buckle a')
            ->where([
                'com_id' => $this->com_id,
                'last_check_user_id'=>$this->user_id,
                'status'=>1,
            ])->count();
        $wsh_jkCount += $tmpCount;
        $this->assign(compact('wsh_jkCount'));
    }

    //我的排名
    private function myRank()
    {
        $userId = session("user_com")['id'];

        //月排行
        $start_time = strtotime(date('Y').'-'.date('m').'-01');
        $end_time = strtotime('+1 month',$start_time)-1;
        $where_1['a.prize_buckle_time'] = ['between', [$start_time, $end_time]];//奖扣时间
        $where_1['a.status'] = 2; //审核通过
        $where_1['c.is_cancellation'] = 0; //未作废
        $where_1['d.type'] = 1; //未冻结
//        $where_1['d.is_sort'] = 1; //参与排名
        $where_1['a.com_id'] = $this->com_id;
        $m_s = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','b.prize_buckle_id=a.id','right')
            ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
            ->join('users d','d.id=c.user_id','left')
            ->group('c.user_id')
            ->where($where_1)
            ->column('c.user_id,COALESCE(sum(IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate)),0) integral_b_add');
        if(!array_search($userId, array_keys($m_s))){
            $m_s[$userId] = 0;
        }
        arsort($m_s);
        $m = array_search($userId, array_keys($m_s));
        if(is_numeric($m)) $m += 1;
        //年排行
        $where_1 = [];
        $start_time = strtotime(date('Y').'-'.'01'.'-01');
        $end_time = strtotime('+1 year',$start_time)-1;
        $where_1['a.prize_buckle_time'] = ['between', [$start_time, $end_time]];//奖扣时间
        $where_1['a.status'] = 2; //审核通过
        $where_1['c.is_cancellation'] = 0; //未作废
        $where_1['a.com_id'] = $this->com_id;
        $where_1['d.type'] = 1; //未冻结
//        $where_1['d.is_sort'] = 1; //参与排名
        $y_s = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','b.prize_buckle_id=a.id','right')
            ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
            ->join('users d','d.id=c.user_id','left')
            ->group('c.user_id')
            ->where($where_1)
            ->column('c.user_id,COALESCE(sum(IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate)),0) integral_b_add');
        if(!array_search($userId, array_keys($y_s))){
            $y_s[$userId] = 0;
        }
        arsort($y_s);
        $y = array_search($userId, array_keys($y_s));
        if(is_numeric($y)) $y += 1;

        //总排行
        $where_1 = [];
        $where_1['a.status'] = 2; //审核通过
        $where_1['c.is_cancellation'] = 0; //未作废
        $where_1['a.com_id'] = $this->com_id;
        $where_1['d.type'] = 1; //未冻结
        $where_1['a.prize_buckle_time'] = ['between', [strtotime('2019-01-01'),time()]];//奖扣时间
//        $where_1['d.is_sort'] = 1; //参与排行
        $t_s = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','b.prize_buckle_id=a.id','right')
            ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
            ->join('users d','d.id=c.user_id','left')
            ->group('c.user_id')
            ->where($where_1)
            ->column('c.user_id,COALESCE(sum(IF(c.piece_rate=0,c.integral_b,c.integral_b*c.piece_rate)),0)+d.base_integral+d.working_age_integral integral_b_add');
        arsort($t_s);
        $t = array_search($userId, array_keys($t_s));
        if(is_numeric($t)) $t += 1;

        $userRank = [
            'month' => [
                'rank'=>$m??0,
                'integral'=>$m_s[$userId]??0
            ],
            'year'  => [
                'rank'=>$y??0,
                'integral'=>$y_s[$userId]??0
            ],
            'total' => [
                'rank'=>$t??0,
                'integral'=>$t_s[$userId]??0
            ],
        ];
        $this->assign(compact('userRank'));
    }

    //我的积分
    private function myIntegral(){
        $userIntegral = [];
        $userId = $this->user_id;
//        $whereIntegral = [
//            'user_id' => $userId,
//            'type' => ['in', '0,1,3'],
//            'month'=> date('m'),
//            'year'=> date('Y')
//        ];
        $s_time_int = strtotime(date('Y-m-01',time()));
        $e_time_int = strtotime('+1 month',$s_time_int)-1;
        //本月日常奖扣
        $prize = SendIntegralNew::statistic_integral($s_time_int,$e_time_int,$userId,0);
        //本月固定积分
        $where_time = [];
        $where_time['create_time'] = ['between',[$s_time_int,$e_time_int]];
        $fixed = M('com_integral_log')->where(['com_id'=>$this->com_id,'user_id'=>$userId,'type'=>1])->where($where_time)->sum('integral_b');
        //本月其他积分
        $other = M('com_integral_log')->where(['com_id'=>$this->com_id,'user_id'=>$userId,'type'=>3])->where($where_time)->sum('integral_b');
//        $userIntegral = db('com_integral_log')
//            ->where($whereIntegral)
//            ->group('type')
//            ->fetchSql()
//            ->column('type,SUM(integral_b ) as integral_b_sum');


        //计算积分对应百分比
        $sum = abs($prize??0) + abs($fixed??0) + abs($other??0);
        if($sum == 0){
            return ;
        }
        $userIntegral[0]  = [];
        $userIntegral[0]['sum']         = $prize??0;
        $userIntegral[0]['percent']     = round(abs($prize??0)/$sum*100);

        $userIntegral[1]  = [];
        $userIntegral[1]['sum']         = $fixed??0;
        $userIntegral[1]['percent']     = round(abs($fixed??0)/$sum*100);

        $userIntegral[3]  = [];
        $userIntegral[3]['sum']         = $other??0;
        $userIntegral[3]['percent']     = round(abs($other??0)/$sum*100);

        $this->assign(compact('userIntegral'));
    }

    /**
     * 我的审核（tab=0）、积分奖扣（tab=1）
     * @param int $tab
     */
    private function checkAward($tab = 0)
    {
        $userId = session("user_com")['id'];
        $where = [];
        if($tab == 0){
            $where = [
                'b.first_check_user_id|b.last_check_user_id'=>$userId
            ];
            $assign = 'userCheck';
        }else{
            $where = [
                'b.record_user_id'=>$userId
            ];
            $assign = 'userAward';
        }

        $join = [
            ['users u','u.id = b.first_check_user_id'],
            ['users uu','uu.id = b.last_check_user_id'],
            ['users uuu','uuu.id = b.record_user_id'],
        ];

        $field = 'b.*, u.name as fname, uu.name as lname, uuu.name as rname';

        $userCheckAward = db('com_integral_prize_buckle')->alias('b')
        ->join($join)->where($where)->whereTime('b.prize_buckle_time', 'month')->field($field)
        ->order('b.create_time desc')
        ->group('b.id')
        ->limit(5)
        ->select();

        $this->assign($assign, $userCheckAward);
        $this->assign('checkAwardStatus', \app\company\model\ComIntegralPrizeBuckle::$status_list);
    }

    //奖扣任务

    /**
     * 奖扣统计
     * @param string $date  d今天，m本月，y本年
     */
    public function rewardTotal($date = 'd')
    {
        if( request()->isAjax() ) {
            if( in_array(input('date'),['d','m','y']) ){
                $date = input('date');
            }else{
                return $this->ajaxReturn(1,'参数错误');
            }
        }
        $tmpTag = '';
        switch ($date){
            case 'd':
                $userRewardTotal = $this->rewardTotalDay();
                $tmpTag = '日';
                break;
            case 'm':
                $userRewardTotal = $this->rewardTotalWeek();
                $tmpTag = '周';
                break;
            case 'y':
                $userRewardTotal = $this->rewardTotalMonth();
                $tmpTag = '月';
                break;
        }

        //计算总比例
        foreach ($userRewardTotal as &$v) {
            if(empty($v)) continue;
            $v['integral_b_del'] = abs($v['integral_b_del']??0);

            $tmptotal = 0;
            $tmptotal = $v['integral_b_del']??0 + $v['integral_b_add']??0;

            //当$a小于、等于、大于$b时 分别返回一个小于、等于、大于0的
            switch ($v['integral_b_del']??0 <=> $v['integral_b_add']??0) {
                case -1:
                    $v['percent'] = round($v['integral_b_del']/$tmptotal*100);
                    break;
                case 0:
                    $v['percent'] = 50;
                    break;
                case 1:
                    $v['percent'] = round($v['integral_b_add']/$tmptotal*100);
                    break;
            }
        }
        //数据组装
        foreach ($userRewardTotal as $key => $vv) {
            $returnData['num'][] = $key.$tmpTag;
            $returnData['people_sum'][]     = $vv['people_sum'] ?? 0;
            $returnData['integral_b_add'][] = $vv['integral_b_add'] ?? 0;
            $returnData['integral_b_del'][] = $vv['integral_b_del'] ?? 0;
            $returnData['percent'][]        = $vv['percent'] ?? 0;
        }
//        var_dump($returnData);die;
        if( request()->isAjax() ) {
            return $this->ajaxReturn(0,'','',$returnData);
        }
        $this->assign(compact('returnData'));
    }

    //奖扣统计-天
    private function rewardTotalDay()
    {
        $res = [];
        for ($i = 0; $i < 7; $i++) {
            $tmpSstrtotime = strtotime('-'.(6-$i).' day');
            $whereTime = [
                strtotime(date('Y-m-d', $tmpSstrtotime)),
                strtotime(date('Y-m-d 23:59:59',$tmpSstrtotime))
            ];
            $res[date('d', $tmpSstrtotime)] = SendIntegralNew::statistic_prize_buckle($whereTime[0],$whereTime[1],$this->user_id);
        }
        return $res;
    }

    //奖扣统计-周
    private function rewardTotalWeek()
    {
        //本月一共多少天
        $monthCountDay = date('t');
        //获取本月第一天的时间戳和时间
        $baseDay = date('Y-m-01',time());
        //给指定时间加N天
        $oneDay = strtotime($baseDay);
        $servenDay = strtotime("+7 day",strtotime($baseDay) );
        $fourteenDay = strtotime("+14 day",strtotime($baseDay) );
        $Twenty_oneDay = strtotime("+21 day",strtotime($baseDay) );
        $lastDay = strtotime( date('Y-m-'.$monthCountDay.' 23:59:59') );

        //本月4周，每周开头和结尾时间
        $tmpArr = [
            [$oneDay, $servenDay],
            [$servenDay+1, $fourteenDay],
            [$fourteenDay+1, $Twenty_oneDay],
            [$Twenty_oneDay+1, $lastDay],
        ];

        $res = [];
        foreach ( $tmpArr as $k=>$v ) {
            $res[$k+1] = SendIntegralNew::statistic_prize_buckle($v[0],$v[1],$this->user_id);
        }
        return $res;
    }

    //奖扣统计-月
    private function rewardTotalMonth()
    {
        //获取当前月
        $month = date('m');

        $res = [];
        for($i = 1; $i <= $month; $i++) {
            //获取指定月份天数
            $lastday = cal_days_in_month(CAL_GREGORIAN, $i, date('Y'));

            $whereTime = [strtotime(date('Y-'.$i.'-01')), strtotime(date('Y-'.$i.'-'.$lastday.' 23:59:59'))];

            $res[$i] = SendIntegralNew::statistic_prize_buckle($whereTime[0],$whereTime[1],$this->user_id);
        }
        return $res;
    }
    //奖扣任务统计
    public function prize_buckle_task(){
        //获取当月配置
        $uid = $this->user_id;
        //查询是否有奖扣任务
        $now_time = time();
        $users = M('com_prize_buckle_config_relation_users')->where('user_id',$uid)->find();
        if(empty($users)){
            $data = [
                'is_integral'=>0,//是否有奖分扣分任务
                'is_man'=>0,//是否有人次任务
                'is_rate'=>0,//是否有比例任务
                'integral_type'=>0,//奖分扣分任务类型  0周  1月
                'man_type'=>1,//人次任务类型  1天 2周  3月
                'integral_reward'=>0,//奖分目标
                'integral_deduct'=>0,//扣分目标
                'man_num'=>0,//人次目标
                'rate'=>0,//比例目标
                'integral_reward_com'=>0,//奖分完成
                'integral_deduct_com'=>0,//扣分完成
                'man_num_com'=>0,//人次完成
                'rate_com'=>0,//比例完成
            ];
        }else{
            //本月配置
            $conf = M('com_prize_buckle_config')->where('id', $users['prize_buckle_id'])->find();
            $data = [
                'is_integral'=>$conf['is_integral'],//是否有奖分扣分任务
                'is_man'=>$conf['is_man'],//是否有人次任务
                'is_rate'=>$conf['is_rate'],//是否有比例任务
                'integral_type'=>$conf['integral_type'],//奖分扣分任务类型  0周  1月
                'man_type'=>$conf['man_type'],//人次任务类型  1天 2周  3月
                'integral_reward'=>$conf['integral_reward'],//奖分目标
                'integral_deduct'=>$conf['integral_deduct'],//扣分目标
                'man_num'=>$conf['man_num'],//人次目标
                'rate'=>$conf['rate'],//比例目标
                'integral_reward_com'=>0,//奖分完成
                'integral_deduct_com'=>0,//扣分完成
                'man_num_com'=>0,//人次完成
                'rate_com'=>0,//比例完成
                'prize_com_rate'=>0,//奖分完成比例
                'buckle_com_rate'=>0,//扣分完成比例
                'people_com_rate'=>0,//人次完成比例
                'rate_com_rate'=>0,//比例完成比例
            ];
            //奖扣分完成值
            if($conf['integral_type'] == 1){//月任务
                $time = date('Y-m',time());
                $start = strtotime($time.'-01');
                $end = strtotime('+1 month -1 day',$start);
            }else{
                $time = strtotime(date('Y-m-01',time()));
                //周时间
                $week_time_1 = $time+7*24*3600;
                $week_time_2 = $week_time_1+7*24*3600;
                $week_time_3 = $week_time_2+7*24*3600;
                if($now_time < $week_time_1){
                    $start = strtotime($time.'-01');
                    $end = $week_time_1;
                }elseif($now_time >= $week_time_1 && $now_time < $week_time_2){
                    $start = $week_time_1;
                    $end = $week_time_2;
                }elseif($now_time >= $week_time_2 && $now_time < $week_time_3){
                    $start = $week_time_2;
                    $end = $week_time_3;
                }else{
                    $start = $week_time_3;
                    $end = strtotime('+1 month -1 day',$start);
                }
            }
            $where = [];
            $where['first_check_user_id'] = $uid; //初审人
            $where['prize_buckle_time'] = ['between', [$start, $end]]; //奖扣时间范围
            $where['status'] = 2; //审核通过
            $res = M('com_integral_prize_buckle')
                ->where($where)
                ->field('COALESCE(sum(integral_b_add),0) integral_b_add
            ,COALESCE(sum(integral_b_del),0) integral_b_del,COALESCE(sum(people_sum),0) people_sum')
                ->find();
            $data['integral_reward_com'] = $res['integral_b_add'];//奖分完成值
            $data['integral_deduct_com'] = $res['integral_b_del'];//扣分完成值
            //人次分完成值
            if($conf['man_type'] == 3){//月任务
                $time = date('Y-m',time());
                $start = strtotime($time.'-01');
                $end = strtotime('+1 month -1 day',$start);

            }elseif($conf['man_type'] == 2){
                $time = strtotime(date('Y-m-01',time()));
                //周时间
                $week_time_1 = $time+7*24*3600;
                $week_time_2 = $week_time_1+7*24*3600;
                $week_time_3 = $week_time_2+7*24*3600;
                if($now_time < $week_time_1){
                    $start = strtotime($time.'-01');
                    $end = $week_time_1;
                }elseif($now_time >= $week_time_1 && $now_time < $week_time_2){
                    $start = $week_time_1;
                    $end = $week_time_2;
                }elseif($now_time >= $week_time_2 && $now_time < $week_time_3){
                    $start = $week_time_2;
                    $end = $week_time_3;
                }else{
                    $start = $week_time_3;
                    $end = strtotime('+1 month -1 day',$start);
                }
            }else{
                $start = strtotime(date('Y-m-d',$now_time));
                $end = $start +24*3600-1;
            }
            $where = [];
            $where['first_check_user_id'] = $uid; //初审人
            $where['prize_buckle_time'] = ['between', [$start, $end]]; //奖扣时间范围
            $where['status'] = 2; //审核通过
            $data['man_num_com'] = M('com_integral_prize_buckle')
                ->where($where)
                ->sum('people_sum');//人次完成值
            //比例完成值
            $time = date('Y-m',time());
            $start = strtotime($time.'-01');
            $end = strtotime('+1 month -1 day',$start);
            $where = [];
            $where['first_check_user_id'] = $uid; //初审人
            $where['prize_buckle_time'] = ['between', [$start, $end]]; //奖扣时间范围
            $where['status'] = 2; //审核通过
            $res = M('com_integral_prize_buckle')
                ->where($where)
                ->field('COALESCE(sum(integral_b_add),0) integral_b_add
            ,COALESCE(sum(integral_b_del),0) integral_b_del,COALESCE(sum(people_sum),0) people_sum')
                ->find();
            if($res['integral_b_del'] == 0 || $res['integral_b_add'] == 0){
                $data['rate_com'] = 0;
            }else{
                if(abs($res['integral_b_del']) >= abs($res['integral_b_add'])){
                    $data['rate_com'] = 100;
                }else{
                    $data['rate_com'] = abs(round($res['integral_b_del']/$res['integral_b_add'],3))*100;
                }

            }

        }
        if($data['integral_reward_com'] == 0 || $data['integral_reward'] == 0){
            $data['prize_com_rate'] = 0;
        }else{
            if(abs($data['integral_reward_com']) >= abs($data['integral_reward'])){
                $data['prize_com_rate'] = 100;
            }else{
                $data['prize_com_rate'] = abs(round($data['integral_reward_com']/$data['integral_reward'],3))*100;
            }

        }
        if($data['integral_deduct_com'] == 0 || $data['integral_deduct'] == 0){
            $data['buckle_com_rate'] = 0;
        }else{
            if(abs($data['integral_deduct_com']) >= abs($data['integral_deduct'])){
                $data['buckle_com_rate'] = 100;
            }else{
                $data['buckle_com_rate'] = abs(round($data['integral_deduct_com']/$data['integral_deduct'],3))*100;
            }

        }
        if($data['man_num_com'] == 0 || $data['man_num'] == 0){
            $data['people_com_rate'] = 0;
        }else{
            if(abs($data['man_num_com']) >= abs($data['man_num'])){
                $data['people_com_rate'] = 100;
            }else{
                $data['people_com_rate'] = abs(round($data['man_num_com']/$data['man_num'],3))*100;
            }

        }
        if($data['rate_com'] == 0 || $data['rate'] == 0){
            $data['rate_com_rate'] = 0;
        }else{
            if(abs($data['rate_com']) >= abs($data['rate'])){
                $data['rate_com_rate'] = 100;
            }else{
                $data['rate_com_rate'] = abs(round($data['rate_com']/$data['rate'],3))*100;
            }

        }
        //判断是否有奖扣权限
        $user_auth = M('com_prize_buckle_relation_users')->where('user_id',$uid)->find();
        if(empty($user_auth)){
            $is_prize_buckle_auth = 0;
        }else{
            $is_prize_buckle_auth = 1;
        }
        $data['is_prize_buckle_auth'] = $is_prize_buckle_auth;
        $this->assign('prize_buckle_data',$data);
    }

}
